<script setup lang="ts">
import { reactive, ref, shallowRef } from 'vue';
import type { FormInstance } from 'vant';
import { shopfahuo, kuaidiList } from '@/common/api/hbMarket';
import { showSuccessToast } from 'vant';
import formPricker from '@/components/formPricker.vue';
import { useLargenScreen } from '@/composables/useLargenScreen';
import type { ColumnsItem } from '@/types/pricker';

// 监听浏览器窗口变化
useLargenScreen();

const emit = defineEmits<{
  (e: 'onRefresh'): void;
}>();

// 定义引用
const formRef = shallowRef<FormInstance>();

const show = ref(false);
const form = reactive({
  oid: '', // 订单号
  kdno: '', // 快递单号
  kdname: '', // 快递名称
});
const emptyForm = JSON.stringify(form);
const kuaidiColumns = ref<ColumnsItem[]>([]);

const onSubmit = async () => {
  try {
    await formRef.value?.validate();
    await shopfahuo({ ...form });
    show.value = false;
    emit('onRefresh');
    showSuccessToast('发货成功');
    return Promise.resolve();
  } catch {
    return Promise.reject();
  }
};

defineExpose({
  open(oid: string) {
    show.value = true;
    form.oid = oid;
  },
});

const beforeClose = (action: string) => {
  if (action === 'cancel') {
    return true;
  } else {
    return new Promise<boolean>((resolve) => {
      onSubmit()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    });
  }
};

const onClosed = () => {
  Object.assign(form, JSON.parse(emptyForm));
  formRef.value?.resetValidation();
};

const getKuaidiList = async () => {
  try {
    const res = await kuaidiList({});
    console.log(res.result.list);
    if (res.result.list?.length) {
      kuaidiColumns.value = res.result.list.map((v: { kdname: string }) => ({ text: v.kdname, value: v.kdname }));
    }
  } catch {
    /** empty */
  }
};
getKuaidiList();
</script>
<template>
  <div class="orderSendDialog">
    <van-dialog v-model:show="show" title="退款审核" show-cancel-button :before-close="beforeClose" @closed="onClosed">
      <van-form class="py-3" label-width="70px" ref="formRef">
        <van-cell-group inset>
          <van-field v-model="form.oid" name="oid" label="订单编号" placeholder="订单编号" readonly />
          <form-pricker v-model="form.kdname" label="快递名称" name="kdname" teleport="body" :columns="kuaidiColumns" />
          <van-field
            v-model="form.kdno"
            name="kdno"
            label="快递单号"
            placeholder="快递单号"
            :rules="[{ required: true, message: '请填写快递单号' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
  </div>
</template>
<style lang="less" scoped>
.orderSendDialog {
}
</style>
